package com.xdan.memory.service;

import cn.hutool.core.date.DateUtil;
import com.lark.oapi.Client;
import com.lark.oapi.service.im.v1.model.*;
import com.xdan.memory.config.RobotConfig;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

@Service
public class ImService {
    @Resource
    private RobotConfig robotConf;

    //    private static final String[] USER_OPEN_IDS = {"ou_a79a0f82add14976e3943f4deb17c3fa", "ou_33c76a4cbeb76bd66608706edb32508e"};
//    private final String[] USER_OPEN_IDS = {"ou_3e3e740550ae923335e055ff6b539f5b"};

//    private Client client = Client.newBuilder(robotConf.getAppId(), robotConf.getAppSecret()).build();


    // 获取会话信息
    public GetChatRespBody GetChatInfo(String chatId) throws Exception {
        GetChatReq req = GetChatReq.newBuilder()
                .chatId(chatId)
                .build();
        Client client = Client.newBuilder(robotConf.getAppId(), robotConf.getAppSecret()).build();
        GetChatResp resp = client.im().chat().get(req);

        if (!resp.success()) {
            throw new Exception(String.format("client.im.chat.get failed, code: %d, msg: %s, logId: %s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        return resp.getData();
    }

    // 更新会话名称
    public void UpdateChatName(String chatId, String chatName) throws Exception {
        UpdateChatReq req = UpdateChatReq.newBuilder()
                .chatId(chatId)
                .updateChatReqBody(UpdateChatReqBody.newBuilder()
                        .name(chatName)
                        .build())
                .build();
        Client client = Client.newBuilder(robotConf.getAppId(), robotConf.getAppSecret()).build();
        UpdateChatResp resp = client.im().chat().update(req);

        if (!resp.success()) {
            throw new Exception(String.format("client.im.chat.update failed, code: %d, msg: %s, logId: %s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }
    }

    public void SendAlertMessage(String chatId, String event, String project, String product, String message, String alarmUser) throws Exception {
        // 截取message的150个字符
//        if (message.length() > 150) {
//            message = message.substring(0, 150);
//        }
        SendMessage(chatId, "interactive", BuildCard("跟进处理", event, project, product, message, alarmUser));
    }

    // 发送报警消息
    public void SendMessage(String chatId, String msgType, String content) throws Exception {
        CreateMessageReq req = CreateMessageReq.newBuilder()
                .receiveIdType("chat_id")
                .createMessageReqBody(CreateMessageReqBody.newBuilder()
                        .receiveId(chatId)
                        .msgType(msgType)
                        .content(content)
                        .build())
                .build();
        Client client = Client.newBuilder(robotConf.getAppId(), robotConf.getAppSecret()).build();
        CreateMessageResp resp = client.im().message().create(req);

        if (!resp.success()) {
            throw new Exception(String.format("client.im.message.create failed, code: %d, msg: %s, logId: %s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }
    }

    public String BuildCard(String buttonName, String event, String project, String product, String message, String alarmUser) throws Exception {
        ClassPathResource resource = new ClassPathResource("card.json");
        InputStream inputStream = resource.getInputStream();
        Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        int ch = 0;
        StringBuilder sb = new StringBuilder();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
//        fileReader.close();
        reader.close();
        String card = sb.toString();


        card = card
                .replace("${button_name}", buttonName)
                .replace("${dateTime}", DateUtil.date(System.currentTimeMillis()).toString())
                .replace("${event}", event)
                .replace("${project}", project)
                .replace("${message}", message)
                .replace("${product}", product)
                .replace("${alarmUser}", alarmUser);
//        System.out.println(card);
        return card;
    }
    // 获取会话历史消息
//    public void ListChatHistory(String chatId) throws Exception {
//        ListMessageReq req = ListMessageReq.newBuilder()
//                .containerIdType("chat")
//                .containerId(chatId)
//                .build();
//
//        ListMessageResp resp = client.im().message().list(req);
//
//        if (!resp.success()) {
//            throw new Exception(String.format("client.im.message.list failed, code: %d, msg: %s, logId: %s",
//                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
//        }
//
//        File file = new File("./src/main/java/com/larksuite/oapi/quick_start/robot/chat_history.txt");
//        FileWriter writer = new FileWriter(file);
//        for (Message item : resp.getData().getItems()) {
//            String senderId = item.getSender().getId();
//            String content = item.getBody().getContent();
//            String createTime = item.getCreateTime();
//
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            createTime = sdf.format(new Date(Long.parseLong(createTime)));
//            writer.write(String.format("chatter(%s) at (%s) send: %s\n", senderId, createTime, content));
//        }
//        writer.close();
//    }

    // 创建报警群并拉人入群
//    public String CreateAlertChat() throws Exception {
//        CreateChatReq req = CreateChatReq.newBuilder()
//                .userIdType("open_id")
//                .createChatReqBody(CreateChatReqBody.newBuilder()
//                        .name("xdan: 线上事故处理")
//                        .description("线上紧急事故处理")
//                        .userIdList(USER_OPEN_IDS)
//                        .build())
//                .build();
//
//        CreateChatResp resp = client.im().chat().create(req);
//
//        if (!resp.success()) {
//            throw new Exception(String.format("client.im.chat.create failed, code: %d, msg: %s, logId: %s",
//                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
//        }
//
//        return resp.getData().getChatId();
//    }

    // 发送报警消息
//    public void SendAlertMessage(String chatId) throws Exception {
//        SendMessage(chatId, "interactive", BuildCard("跟进处理"));
//    }


//    public void SendAlertMessage(String chatId, String event, String project, String product, String message) throws Exception {
//        SendMessage(chatId, "interactive", BuildCard("跟进处理", event, project, product, message));
////        SendMessage(chatId, "interactive", BuildCard(event, project, product, message));
//    }


//    private String UploadImage() throws Exception {
//        File file = new File("./src/main/java/com/larksuite/oapi/quick_start/robot/alert.png");
//        CreateImageReq req = CreateImageReq.newBuilder()
//                .createImageReqBody(CreateImageReqBody.newBuilder()
//                        .imageType("message")
//                        .image(file)
//                        .build())
//                .build();
//
//        CreateImageResp resp = client.im().image().create(req);
//
//        if (!resp.success()) {
//            throw new Exception(String.format("client.im.image.create failed, code: %d, msg: %s, logId: %s",
//                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
//        }
//
//        return resp.getData().getImageKey();
//    }


//    public String BuildCard(String event, String project, String product, String message) throws Exception {
////        String path = Objects.requireNonNull(this.getClass().getClassLoader().getResource("card.json")).getPath();
//        // 上传图片
////        String imageKey = UploadImage();
////        String path = Objects.requireNonNull(this.getClassLoader().getResource("card.json")).getPath();
//        // 获取卡片结构
////        File jsonFile = new File(path);
//        File jsonFile = new File("./memory-alarm/src/main/java/com/xdan/memory/robot/card.json");
//        FileReader fileReader = new FileReader(jsonFile);
//        Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
//        int ch = 0;
//        StringBuilder sb = new StringBuilder();
//        while ((ch = reader.read()) != -1) {
//            sb.append((char) ch);
//        }
//        fileReader.close();
//        reader.close();
//        String card = sb.toString();
//
//
//        card = card
//                .replace("${dateTime}", DateUtil.date(System.currentTimeMillis()).toDateStr())
//                .replace("${event}", event)
//                .replace("${project}", project)
//                .replace("${message}", message)
//                .replace("${product}", product);
//
//        return card;
//    }


//    // 构建卡片
//    public String BuildCard(String buttonName, String event, String project, String product, String message) throws Exception {
////        String path = Objects.requireNonNull(this.getClass().getClassLoader().getResource("card.json")).getPath();
//        // 上传图片
////        String imageKey = UploadImage();
////        String path = Objects.requireNonNull(this.getClassLoader().getResource("card.json")).getPath();
//        // 获取卡片结构
////        File jsonFile = new File(path);
//        File jsonFile = new File("./memory-alarm/src/main/java/com/xdan/memory/robot/card.json");
//        FileReader fileReader = new FileReader(jsonFile);
//        Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
//        int ch = 0;
//        StringBuilder sb = new StringBuilder();
//        while ((ch = reader.read()) != -1) {
//            sb.append((char) ch);
//        }
//        fileReader.close();
//        reader.close();
//        String card = sb.toString();
//
//        card = card.replace("${button_name}", buttonName);
//        card = card.replace("${dateTime}", DateUtil.date(System.currentTimeMillis()).toString());
//        card = card.replace("${event}", event);
//        card = card.replace("${project}", project);
//        card = card.replace("${message}", message);
//        card = card.replace("${product}", product);
//
//        return card;
//    }

//
//    // 构建卡片
//    public String BuildCard(String buttonName) throws Exception {
//        // 上传图片
////        String imageKey = UploadImage();
//
//        // 获取卡片结构
//        File jsonFile = new File("./src/main/java/com/xdan/memory/robot/card.json");
//        FileReader fileReader = new FileReader(jsonFile);
//        Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
//        int ch = 0;
//        StringBuilder sb = new StringBuilder();
//        while ((ch = reader.read()) != -1) {
//            sb.append((char) ch);
//        }
//        fileReader.close();
//        reader.close();
//        String card = sb.toString();
//
////        card = card.replace("${image_key}", imageKey);
//        card = card.replace("${button_name}", buttonName);
//        // 我需要生成一个时间 时间的格式为yyyy-MM-dd HH:mm:ss
//
//        Date date3 = DateUtil.date(System.currentTimeMillis());
//        card = card.replace("${dateTime}", date3.toString());
//        card = card.replace("${event}", "事件消息");
//        card = card.replace("${project}", "xdan-memory");
//        card = card.replace("${message}", "这是错误相关的消息");
//
//        return card;
//    }


}